from __future__ import absolute_import
import logging
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from django.contrib import auth
from django.conf import settings
from user.models import PlotoUser
from common.tools import auth_request

logger = logging.getLogger(__name__)


# Create your views here.
class UserLogin(APIView):
    permission_classes = (AllowAny,)

    @auth_request
    def get(self, request):
        return Response({"username": str(request.user)})

    def post(self, request):
        """
        内部用户登录，包括django admin后台，如果有用户需要程序中调用平台接口
        需先调用此接口，获取sessionid，并将其加入request header中，才能继续调用
        :param request:
        :return:
        """
        data = request.data
        user_name = data.get("username", "")
        if not user_name:
            user_name = data.get("user")
        password = data.get("password", "xxx.xxx")
        user = auth.authenticate(username=user_name, password=password)
        if user is None:
            # 鉴权失败，记录告警日志
            logger.warning("user login fail, name or password is wrong, username: %s", user_name)
            return Response({"login": "failed", "username": user_name}, status=status.HTTP_401_UNAUTHORIZED)

        ploto_user = PlotoUser.objects.get(user_id=user.id)
        if ploto_user is None or ploto_user.type != 0:
            # 账号类型错误，AD域账号使用密码登录，记录告警日志
            logger.warning("user login fail, not ploto user, username: %s", user_name)
            return Response({"login": "failed", "username": user_name}, status=status.HTTP_401_UNAUTHORIZED)

        if user.is_active:
            # 鉴权成功且是激活的账号
            auth.login(request, user)
            request.session["username"] = user_name

            response = Response({"login": "succeed", "CSRFToken": request.META["CSRF_COOKIE"]})
            response.set_cookie(key="username", value=user_name, max_age=settings.SESSION_COOKIE_AGE, samesite=None)
            logger.info("user login succeed, username: %s", user_name)

            return response
        else:
            # 账号未激活，记录info日志
            logger.info("user login fail, not active, username: %s", user_name)
            return Response({"login": "failed", "username": user_name}, status=status.HTTP_401_UNAUTHORIZED)


class UserLogout(APIView):
    def post(self, request):
        """
        用户登出接口
        :param request:
        :return:
        """
        user_name = str(request.user)
        logger.info("user logout, username: %s", user_name)
        auth.logout(request)
        return Response({'logout': "succeed", "username": user_name}, status=status.HTTP_200_OK)


class ADUserLogin(APIView):
    def post(self, request):
        """
        AD域账号登录接口，若无用户则新增，使用默认密码
        AD域账号不允许使用账号密码登录
        :param request:
        :return:
        """
        return Response({}, status=status.HTTP_200_OK)
